﻿using Dotnet.Code;
using Dotnet.TopApi;
using HtmlAgilityPack;
using Jayrock.Json.Conversion.Converters;
using My.Dotnet.Net;
using ScrapySharp.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Dotnet.Sui
{
    public partial class Sui
    {
        protected string _cookie = "";
        public Sui(){}
        public Sui(string cookie)
        {
            this._cookie = cookie;
        }
        //同步随信息
        public void SuiCateAccountSame(string cookie,Action<SuiDoResponse> fn)
        {
            SuiClient client = new SuiClient();

            DoAccountRequest req1 = new DoAccountRequest();
            req1.Cookie = cookie;
            var resp1 = client.Execute<DoAccountResponse>(req1);
            resp1.ParseCateAccount(resp1.Body);
            fn(resp1);
            ///////////////////////////////////////////////
            DoBudgetCategoryRequest req2 = new DoBudgetCategoryRequest();
            req2.Cookie = cookie;
            var resp2 = client.Execute<DoBudgetCategoryResponse>(req2);
            resp2.ParseCateAccount(resp2.Body);
            fn(resp2);
            ////////////////////////////////////////////////
            DoIncomeCategoryRequest req3 = new DoIncomeCategoryRequest();
            req3.Cookie = cookie;
            var resp3 = client.Execute<DoIncomeCategoryResponse>(req3);
            resp3.ParseCateAccount(resp3.Body);
            fn(resp3);
            /////////////////////////////////////////////
            DoMemberRequest req4 = new DoMemberRequest();
            req4.Cookie = cookie;
            var resp4 = client.Execute<DoMemberResponse>(req4);
            resp4.ParseCateAccount(resp4.Body);
            fn(resp4);
            //////////////////////////////////////////////
            DoProjectCategoryRequest req5 = new DoProjectCategoryRequest();
            req5.Cookie = cookie;
            var resp5 = client.Execute<DoProjectCategoryResponse>(req5);
            resp5.ParseCateAccount(resp5.Body);
            fn(resp5);
            ////////////////////////////////////////////
            DoStoreCategoryRequest req6 = new DoStoreCategoryRequest();
            req6.Cookie = cookie;
            var resp6 = client.Execute<DoStoreCategoryResponse>(req6);
            resp6.ParseCateAccount(resp6.Body);
            fn(resp6);
        }
        /// <summary>
        /// 查找账单是否记过
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="time">时间</param>
        /// <param name="memo"></param>
        /// <param name="price">价格</param>
        /// <returns></returns>
        public Dotnet.Sui.List SuiFindById(string id)
        {
            SuiClient client = new SuiClient();
            TallyNewRmiRequest req = new TallyNewRmiRequest();
            req.Cookie = this._cookie;
            req.Note= id.Substring(id.Length-20);
           TallyNewRmiResponse resp = client.Execute<TallyNewRmiResponse>(req);
            if (resp.groups.Count == 0) return null;
            return resp.groups[0].list[0];
        }
        public Dotnet.Sui.List SuiFindByTimeAndPrice(string time,string price)
        {
            SuiClient client = new SuiClient();
            TallyNewRmiRequest req = new TallyNewRmiRequest();
            req.Cookie = this._cookie;
            req.BeginDate =DateTime.Parse(time).ToString("yyyy.MM.dd");
            req.EndDate = DateTime.Parse(time).ToString("yyyy.MM.dd");
            TallyNewRmiResponse resp = client.Execute<TallyNewRmiResponse>(req);
            if (resp.groups.Count == 0) return null;
            decimal je=decimal.Parse(price);
            Dotnet.Sui.List tmp = resp.groups[0].list.FirstOrDefault(t => t.itemAmount == je);
            if(tmp == null) return null;
            return tmp;
        }
        /// <summary>
        /// 判断是否已记过，已记返回true,未记返回false
        /// </summary>
        /// <param name="id"></param>
        /// <param name="time"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        public Dotnet.Sui.List IsExistSui(string id, string time, string price)
        {
            Dotnet.Sui.List list = SuiFindById(id);
            if(list!=null) return list;
            list = SuiFindByTimeAndPrice(time, price);
            if(list==null) return null;
            if (list.memo.Contains(id)) return list;
            return null;
        }

        public bool Sui收(string id,string category,string account,string price, string time,
            string memo,string project,string member,string store,Action<string> fn=null)
        {
            try
            {
                string info = $"id:{id} 收入分类:{category} 账号:{account} 金额:{price} 备注【{memo}】";
                TallyIncomeRmiRequest req = new TallyIncomeRmiRequest();
                SuiClient client = new SuiClient();
                req.Cookie = _cookie;
                req.Category = category;
                req.Account = account;
                req.Price = price;
                req.Time = time;
                req.Memo = memo;
                req.Project = project;
                req.Member = member;
                req.Store = store;
                Dotnet.Sui.List isExistList =IsExistSui(id,time,price);
                if (isExistList ==null)//未记过
                {
                    TallyIncomeRmiResponse resp = client.Execute<TallyIncomeRmiResponse>(req);
                    if (fn != null) fn($"【记账成功】{resp.ReqUrl} {resp.Body} {info}");
                    return true;
                }
                else //已记则更新
                {
                    req.Id = isExistList.sId;
                    if (!isExistList.memo.StartsWith("自收"))
                    {
                        req.Memo = $"{memo}【{isExistList.memo}】";
                    }
                   
                    TallyIncomeRmiResponse resp = client.Execute<TallyIncomeRmiResponse>(req);
                    if (fn != null) fn($"【更新成功】{resp.ReqUrl} {resp.Body} {info}");
                }
                return true;
            }
            catch (Exception)
            {
                throw;
            }

        }

        public bool Sui支(string id, string category, string account, string price, string time,
            string memo, string project, string member, string store, Action<string> fn = null)
        {
            try
            {
                string info = $"id:{id} 支出分类:{category} 账号:{account} 金额:{price} 备注【{memo}】";
                TallyPayOutRmiRequest req = new TallyPayOutRmiRequest();
                SuiClient client = new SuiClient();
                req.Cookie = _cookie;
                req.Category = category;
                req.Account = account;
                req.Price = price;
                req.Time = time;
                req.Memo = memo;
                req.Project = project;
                req.Member = member;
                req.Store = store;
                Dotnet.Sui.List isExistList = IsExistSui(id, time, price);
                if(isExistList == null)
                {
                    TallyPayOutRmiResponse resp = client.Execute<TallyPayOutRmiResponse>(req);
                    if (fn != null) fn($"【记账成功】{resp.ReqUrl} {resp.Body} {info}");
                }
                else
                {
                    req.Id = isExistList.sId;
                    if (!isExistList.memo.StartsWith("自支"))
                    {
                        req.Memo = $"{memo}【{isExistList.memo}】";
                    }
                    TallyPayOutRmiResponse resp = client.Execute<TallyPayOutRmiResponse>(req);
                    if (fn != null) fn($"【更新成功】{resp.ReqUrl} {resp.Body} {info}");
                }
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Sui转(string id, string out_account, string in_account, string price, string time,
    string memo, string project, string member, string store, Action<string> fn = null)
        {
            try
            {
                string info = $"id:{id} 转出账号:{out_account} 转入账号:{in_account} 金额:{price} 备注【{memo}】";
                TallyTransferRmiRequest req = new TallyTransferRmiRequest();
                SuiClient client = new SuiClient();
                req.Cookie = _cookie;
                req.Out_account = out_account;
                req.In_account = in_account;
                req.Price = price;
                req.Time = time;
                req.Memo = memo;
                req.Project = project;
                req.Member = member;
                req.Store = store;
                Dotnet.Sui.List isExistList = IsExistSui(id, time, price);
                if (isExistList == null)
                {
                    TallyTransferRmiResponse resp = client.Execute<TallyTransferRmiResponse>(req);
                    if (fn != null) fn($"【记账成功】{resp.ReqUrl} {resp.Body} {info}");
                }
                else
                {
                    req.Id = isExistList.sId;
                    if (!isExistList.memo.StartsWith("自支"))
                    {
                        req.Memo = $"{memo}【{isExistList.memo}】";
                    }
                    TallyTransferRmiResponse resp = client.Execute<TallyTransferRmiResponse>(req);
                    if (fn != null) fn($"【更新成功】{resp.ReqUrl} {resp.Body} {info}");
                }
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}